<template>
  <PageWrapper title="创建任务" contentBackground>
    <template #extra>
      <a-space :size="50">
        <a-button @click="doPrev" v-if="current > 0">上一步</a-button>
        <a-button type="primary" @click="doNext" v-if="current > 0 && current < 3">
          {{ current == 2 ? '提交' : '下一步' }}
        </a-button>
      </a-space>
    </template>
    <div class="p-3">
      <a-steps :current="current" :items="items" />
    </div>
    <div v-show="current == 0">
      <ImpExcel @success="loadDataSuccess" dateFormat="YYYY-MM-DD">
        <a-button class="m-3"> 选择导入Excel </a-button>
      </ImpExcel>
    </div>
    <div v-show="current == 1">
      <BasicForm @register="registerForm" />
    </div>
    <div v-show="current == 2">
      <BasicTable
        @register="registerTable"
        :rowSelection="selectMethods.rowSelection"
        @edit-end="handleEditEnd"
      />
    </div>
  </PageWrapper>
</template>
<script setup lang="ts">
  import PageWrapper from '@/components/Page/src/PageWrapper.vue';
  import { ImpExcel, ExcelData } from '@/components/Excel';
  import { ref } from 'vue';
  import BasicTable from '@/components/Table/src/BasicTable.vue';
  import { BasicColumn } from '@/components/Table';
  import { useListTable } from '@/hooks/system/useListPage';
  import BasicForm from '@/components/Form/src/BasicForm.vue';
  import ApiV1 from '@/views/common/operate/ApiV1';

  import { forIn, includes, isNil, isString, keys, map } from 'lodash-es';
  import { Steps as ASteps, Space as ASpace } from 'ant-design-vue';
  import { formatToDateTime } from '@/utils/dateUtil';
  import { useQianguaFormSchema } from '@/views/dp_platform/qiangua.data';
  import { addtopic } from '@/views/dp_platform/qiangua.api';

  const current = ref<number>(0);
  const steps = [{ title: '选择导入文件' }, { title: '创建任务' }, { title: '选择导入数据' }];
  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  const doPrev = () => {
    current.value--;
  };
  //'达人账号名'=>'', '达人ID', '达人主页链接', '达人链接地址', '达人昵称'
  const accetpObject = {
    达人昵称: 'name',
    达人ID: 'redId',
    达人主页链接: 'linkUrl',
    达人账号名: 'name',
    达人链接地址: 'linkUrl',
  };

  const doNext = async () => {
    try {
      await formMethods.validate();
      //处理提交数据
      if (current.value == 2) {
        await methods.handleSubmit();
      } else {
        current.value++;
        if (current.value == 2) {
          const field = formMethods.getFieldsValue();
          const {
            header,
            results,
            meta: { sheetName },
            startRow,
          } = loadDataList[field['sheetType']] as ExcelData;

          const columns: BasicColumn[] = [];
          for (const title of header) {
            if (includes(keys(accetpObject), title)) {
              const item: BasicColumn = { title, dataIndex: title, edit: true };
              if (title.indexOf('链接') == -1) {
                item['width'] = 200;
              }
              columns.push(item);
            }
          }

          const len = isNil(field['end_row']) ? results.length : field['end_row'] - 1 - startRow;

          const data = results.splice(field['start_row'] - 2 - startRow, len);

          setProps({ title: sheetName });
          setColumns(columns);
          setTableData(data);
          await reload();
        }
      }
    } catch (e) {}
  };
  const { registerForm, formMethods, methods } = ApiV1.usePageHandle({
    formProps: {
      schemas: useQianguaFormSchema(),
      baseColProps: { span: 8 },
      showSubmitButton: false,
      showResetButton: false,
    },
    saveFn: addtopic,
    beforeSubmit: async (values) => {
      const columns = map(getColumns(), (item) => item['dataIndex']);
      let data = getSelectRows();
      if (data.length == 0) {
        data = getDataSource();
      }
      const postData = map(data, (item) => {
        const maps = {};
        forIn(item, (value, key) => {
          if (isString(key) && includes(columns, key)) {
            maps[accetpObject[key]] = value;
          }
        });
        return maps;
      });
      values['pgy_data'] = postData;
      return values;
    },
    title: '',
  });
  const [
    registerTable,
    { setColumns, setTableData, reload, setProps, getDataSource, getColumns, getSelectRows },
    selectMethods,
  ] = useListTable({
    rowKey: '',
    showTableSetting: false,
    immediate: true,
    useSearchForm: false,
    showActionColumn: false,
  });

  const handleEditEnd = ({ record, index, key, value }: Recordable) => {
    //console.log(record, index, key, value);
    return false;
  };
  let loadDataList: Array<ExcelData> = [];
  async function loadDataSuccess(obj) {
    const { excelDataList, file } = obj;
    current.value++;
    const name = (file as File).name.replace(/\.[^/.]+$/, '');
    await formMethods.setFieldsValue({ title: name + '_' + formatToDateTime() });
    const excelList = Array.from<ExcelData>(excelDataList);
    loadDataList = excelList;
    await formMethods.updateSchema([
      { field: 'datetime', ifShow: false },
      { field: 'condition.end_date', ifShow: false },
      { field: 'condition.start_date', ifShow: false },
      { field: 'condition.pagesize', ifShow: false },
      { field: 'condition.title', ifShow: false },
    ]);
    await formMethods.setFieldsValue({ type: 1 });
    if (excelList.length > 1) {
      const options = map(excelList, (item: ExcelData, index) => {
        return {
          label: item.meta.sheetName,
          value: index,
        };
      });
      await formMethods.updateSchema({
        field: 'sheetType',
        required: true,
        componentProps: {
          options: options,
          onChange: async (e) => {
            await formMethods.setFieldsValue({
              start_row: (excelDataList[e] as ExcelData).startRow + 2,
            });
          },
        },
        show: true,
      });
    } else {
      await formMethods.updateSchema({
        field: 'sheetType',
        show: false,
      });
      await formMethods.setFieldsValue({
        start_row: (excelDataList[0] as ExcelData).startRow + 2,
        end_row: '',
        sheetType: 0,
      });
    }
  }
</script>
